using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace AdRotator.Networking
{
    internal class Network
    {
        private static string CurrentIP;
        const string IPValidatorHost = "http://compiledexperience.com/windows-phone-7/my-ip";


        public async static Task<string> GetStringFromURL(string url)
        {
            HttpClientHandler handler = new HttpClientHandler { UseDefaultCredentials = true, AllowAutoRedirect = true };
            HttpClient client = new HttpClient(handler);
            client.MaxResponseContentBufferSize = 196608;
            HttpResponseMessage response = await client.GetAsync(url);

            response.EnsureSuccessStatusCode();

            string responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }


        public async static Task<Stream> GetStreamFromURL(string url)
        {
            HttpClientHandler handler = new HttpClientHandler { UseDefaultCredentials = true, AllowAutoRedirect = true };
            HttpClient client = new HttpClient(handler);
            client.MaxResponseContentBufferSize = 196608;
            HttpResponseMessage response = await client.GetAsync(url);

            response.EnsureSuccessStatusCode();

            var responseBody = await response.Content.ReadAsStreamAsync();
            return responseBody;
        }

        internal async static Task<string> GetDeviceIP(Action<string, Exception> callback)
        {
            if (CurrentIP != null && !string.IsNullOrEmpty(CurrentIP))
            {
                return CurrentIP;
            }
            var resultString = await GetStringFromURL(IPValidatorHost);
            var value = (resultString).Split(new Char[] { '"' });
            if (value.Length > 2)
            {
                var iPValue = (value[3]).Split(new Char[] { '.' });
                if (iPValue.Length == 4)
                {
                    CurrentIP = value[3];
                    return CurrentIP;
                }
            }

            return null;
        }

    }
}
